package com.guyu.plugin.redisson.util;


import cn.hutool.extra.spring.SpringUtil;
import com.guyu.plugin.redisson.key.ILockKey;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;

@Slf4j
public class LockUtils {

    private static final RedissonClient CLIENT = SpringUtil.getBean(RedissonClient.class);

    /**
     * 尝试加锁
     */
    public static boolean tryLock(RLock rLock, ILockKey iLockKey) {
        try {
            return rLock.tryLock(iLockKey.getWaitTime(), iLockKey.getExpire(), iLockKey.getUnit());
        } catch (InterruptedException e) {
            log.error(" tryLock error, lock:{}", rLock.getName(), e);
        }
        return false;
    }

    /**
     * 获取读写锁
     */
    public static RLock getLock(ILockKey iLockKey, Object... key) {
        String cacheKey = RedisUtils.getCacheKey(iLockKey, key);
        return CLIENT.getLock(cacheKey);
    }

    /**
     * 获取并尝试加锁
     */
    public static RLock getLockAndTry(ILockKey iLockKey, Object... key) {
        RLock rLock = getLock(iLockKey, key);
        boolean result = tryLock(rLock, iLockKey);
        return result ? rLock : null;
    }

    /**
     * 获取读写锁
     */
    public static RReadWriteLock getReadWriteLock(ILockKey iLockKey, Object... key) {
        String cacheKey = RedisUtils.getCacheKey(iLockKey, key);
        return CLIENT.getReadWriteLock(cacheKey);
    }
}
